package com.dingpeikeji.quickdeer.modules.wx.common.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.isouland.cpwx.api.base.WxOAuthAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dingpeikeji.quickdeer.core.common.config.Global;
import com.dingpeikeji.quickdeer.core.modules.driver.entity.TDrivers;
import com.dingpeikeji.quickdeer.core.modules.driver.service.TDriversService;
import com.dingpeikeji.quickdeer.core.modules.sys.entity.User;
import com.dingpeikeji.quickdeer.modules.wx.interceptor.OAuthInterceptor;
import com.dingpeikeji.quickdeer.modules.wx.member.service.WxMemberService;
import com.dingpeikeji.quickdeer.modules.wx.util.TimedTask;
import com.tencent.common.Configure;

@Controller
@RequestMapping("${wxPath}")
public class OAuth {
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	@Autowired
	private TDriversService tDriversService;
	@Autowired
	private WxMemberService memberService;
	
//	// 公众号的功能模块
//	public static final String FUNC_DRIVER_USER = "d"; // 司机用户
//	public static final String FUNC_PUBUSER_USER = "pu"; // 普通用户
	
	// session中的身份
	public static final String SESSION_DEBUG = "isDebug"; // 调试模式
	public static final String SESSION_DRIVER = "driverPermission"; // 司机身份
	public static final String SESSION_PUBUSER = "front_user"; // 普通身份
	public static final String FRONT_USER_IN_SESSION = "front_user";
	
	// 无权页
	public static final String NOPERMISSION = "noPermission";
	public static final String REDIRECT_NOPERMISSION = "redirect:"+Global.getWxPath()+"/"+NOPERMISSION;
	
	// 司机端oauth地址
	public static final String OAUTH_URL_DRIVER = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Configure.getAppid()+"&redirect_uri=https%3a%2f%2fwww.xiakeyueche.com%2fwx%2fdriver%2ftoIndex&response_type=code&scope=snsapi_base&state=d#wechat_redirect";
	//测试用的
	public static final String OAUTH_DRIVER = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+TimedTask.appid+"&redirect_uri=http%3a%2f%2fxiaopihaixxoo.51vip.biz%2fquickdeer%2fwx%2fdriver%2ftoIndex&response_type=code&scope=snsapi_base&state=d#wechat_redirect";
	
	// 大众用户oauth地址
	public static final String OAUTH_URL_PUBUSER = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Configure.getAppid()+"&redirect_uri=https%3A%2F%2Fwww.xiakeyueche.com%2Fwx&response_type=code&scope=snsapi_base&state=pu#wechat_redirect";
	public static final String OAUTH_BACK_URL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+Configure.getAppid()+"&redirect_uri=https%3A%2F%2Fwww.xiakeyueche.com%2Fwx&response_type=code&scope=snsapi_base&state=back#wechat_redirect";
	
	/**
	 * 	司机发车
	 *  https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx70cbd1f125e9b16e
	 *  &redirect_uri=https%3A%2F%2Fwww.xiakeyueche.com%2Fwx
	 *  &response_type=code&scope=snsapi_base&state=d#wechat_redirect
	 *  大众用户
	 *  https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx70cbd1f125e9b16e
	 *  &redirect_uri=https%3A%2F%2Fwww.xiakeyueche.com%2Fwx
	 *  &response_type=code&scope=snsapi_base&state=pu#wechat_redirect
	 */
	@RequestMapping("")
	public String oauth(HttpServletRequest request,HttpServletResponse response, String code, String state, Model model) throws IOException{
		logger.debug("开始认证微信身份，code={}，state={}", code, state);
		if(StringUtils.isEmpty(code) || StringUtils.isEmpty(state)){
			return REDIRECT_NOPERMISSION;
		}
		String openid = WxOAuthAPI.getOpenid(Configure.getAppid(), Configure.getAppsecret(), code);
		if(!StringUtils.isEmpty(openid) && state.equals("d")) {
			logger.debug("司机用户访问");
			TDrivers driver = (TDrivers)request.getSession().getAttribute(OAuth.SESSION_DRIVER);
			if (driver == null){
				// 身份认证
				TDrivers query = new TDrivers();
				query.setWechatid(openid);
				List<TDrivers> driverList = tDriversService.findList(query);
				if(driverList!=null && !driverList.isEmpty()){ // 认证通过
					request.getSession().setAttribute(OAuth.SESSION_DRIVER, driverList.get(0));
					return "redirect:"+Global.getWxPath()+"/d/realschevehi/taskList";
				} else { // 去绑定
					return "redirect:"+Global.getWxPath()+"/bind?openid="+openid;
				}
			} else {
				return "redirect:"+Global.getWxPath()+"/d/realschevehi/taskList";
			}
		}
		if(!StringUtils.isEmpty(openid) && (state.equals("pu")||state.equals("back"))) {
			logger.debug("普通用户访问");
			User commonUser = (User)request.getSession().getAttribute(OAuth.SESSION_PUBUSER);
			if (commonUser == null){
				// 身份认证
				User query = new User();
				query.setWechatId(openid);
				List<User> userList = memberService.findList(query);
				if(userList!=null && !userList.isEmpty()){ // 认证通过
					request.getSession().setAttribute(OAuth.FRONT_USER_IN_SESSION, userList.get(0));
				}
			}
			if(state.equals("back")) {
				// 返回页面，先从地址参数中获取返回路径，如果没有则从session中获取
				String backPage = (String)request.getSession().getAttribute(OAuthInterceptor.WX_BACK_URL_IN_SESSION);
				return "redirect:"+backPage;
			}
			return "redirect:"+Global.getWxPath()+"/pu/index";
		}
		if(!StringUtils.isEmpty(openid)) {
			return "wx/modules/base/index";
		}
		return REDIRECT_NOPERMISSION;
	}
	
	/**
	 * 无权限
	 * @return
	 */
	@RequestMapping("noPermission")
	public String nopermission(){
		return "wx/modules/common/noPermission";
	}
	
	public static void noPermission(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path;
		response.sendRedirect(basePath+Global.getWxPath()+"/"+OAuth.NOPERMISSION);
	}
}
